package util;

import java.io.Serializable;
import java.util.List;
import org.hibernate.criterion.DetachedCriteria;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.transaction.annotation.Transactional;

/*
 * 通用DAO�?
 * �?有DAO的父�?
 */
public abstract class GeneralDaoImpl<K, T> extends HibernateDaoSupport
	implements GeneralDao<K, T>{
		private Class cla = null;	
		public GeneralDaoImpl(Class tagcla) {
			this.cla = tagcla;
		}
		/* (non-Javadoc)
		 * @see com.dx.util.GeneralDao#delete(T)
		 */
		@Transactional
		public void delete(T entity) {	
			this.getHibernateTemplate().delete(entity);		
		}
		/* (non-Javadoc)
		 * @see com.dx.util.GeneralDao#save(T)
		 */
		@Transactional
		public void save(T entity) {
			this.getHibernateTemplate().save(entity);		
		}
		/* (non-Javadoc)
		 * @see com.dx.util.GeneralDao#update(T)
		 */
		@Transactional
		public void update(T entity) {
			this.getHibernateTemplate().update(entity);
		}
		/* (non-Javadoc)
		 * @see com.dx.util.GeneralDao#get(K)
		 */
		@SuppressWarnings("unchecked")
		public T get(K oid) {		
			return (T)this.getHibernateTemplate().get(cla, (Serializable)oid);
		}
		/* (non-Javadoc)
		 * @see com.dx.util.GeneralDao#load(K)
		 */
		@SuppressWarnings("unchecked")
		public T load(K oid) {
			return (T)this.getHibernateTemplate().load(cla, (Serializable)oid);
		}
		/* (non-Javadoc)
		 * @see com.dx.util.GeneralDao#saveOrUpdate(T)
		 */
		@Transactional
		public void saveOrUpdate(T entity) {		
			getHibernateTemplate().saveOrUpdate(entity);
		}
		
		/* (non-Javadoc)
		 * @see com.dx.util.GeneralDao#deleteById(K)
		 */
		@Transactional
		public void deleteById(K id) {
			this.delete(this.get(id));
		}
		
		/* (non-Javadoc)
		 * @see com.dx.util.GeneralDao#merge(T)
		 */
		@SuppressWarnings("unchecked")
		@Transactional
		public T merge(T entity){
			return (T)this.getHibernateTemplate().merge(entity);
		}
		/* (non-Javadoc)
		 * @see com.dx.util.GeneralDao#list()
		 */
		@SuppressWarnings("unchecked")
		public java.util.List<T> list() {
			DetachedCriteria c = DetachedCriteria.forClass(this.cla);
			return (java.util.List<T>)this.getHibernateTemplate().findByCriteria(c);
		};
		/* (non-Javadoc)
		 * @see com.dx.util.GeneralDao#has(K)
		 */
		public boolean has(K oid){
			if(oid == null || oid.equals(""))return false;
			return (this.get(oid) != null);
		}
		
		
		public boolean isNull(Object obj){
			return obj == null || obj.toString().trim().equals("");
		}
		/**
		 * 根据某个属性加实体
		 */
		public T get(String propName, Object val){
			String hql = "from " + this.cla.getName() + " a where a." + propName + "=?";
			List ls = this.getHibernateTemplate().find(hql, new Object[]{
					val
			});
			if(ls.isEmpty()) return null;
			return (T)ls.get(0);
		}
}
